package com.ht.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ht.api.annotate.OpenApi;
import com.ht.api.bean.AjaxResult;
import com.ht.api.constant.CacheConstants;
import com.ht.api.constant.Constants;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.util.RedisUtil;
import com.ht.api.service.LoginService;
import com.ht.api.thread.AsyncFactory;
import com.ht.api.util.JwtUtils;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 登录
 * @author asq
 * @createTime 2024年12月21日 20:21:44
 */
@RestController
public class LoginController {
	@Autowired
	private LoginService loginService;

	/**
	 * 登入
	 * @param req
	 * @param username 用户名
	 * @param pwd 密码
	 * @return
	 */
	@PostMapping("/login")
	@OpenApi
	public AjaxResult login(HttpServletRequest req, @RequestParam(defaultValue = "") String username,
			@RequestParam(defaultValue = "") String pwd) {
		return loginService.login(username, pwd);
	}

	/**
	 * 登出
	 * @param req
	 * @return
	 */
	@PostMapping("/login-out")
	public AjaxResult loginOut(HttpServletRequest req) {
		String username = JwtUtils.getUsername(req);
		if (StrUtil.isNotBlank(username)) {
			HtTaskExecutor.execute(AsyncFactory.recordLogininfor(username, Constants.LOGOUT, "退出登陆"));
			RedisUtil.delete(CacheConstants.KEY_USER + username);
		}
		return AjaxResult.success();
	}
}
